import React, {useContext, useEffect, useState} from 'react';
import {Avatar, Calendar, Card, Skeleton} from "antd";
import classes from './index.module.scss'
import 'dayjs/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import {useDispatch, useSelector} from "react-redux";
import {getArticleIntro, updateArticleList} from "../../../store/frontDesk/articleSlice";
import Sort from "../../../component/frontDesk/Sort";
import Article from "../../../component/frontDesk/Article";
import history from "../../../utils/history";
import {reqGetArticleLikes, reqGetJudgeLike, reqLike} from "../../../api/frontDesk/frontDeskApi";
import {likeIdsContext} from "../../../store/frontDesk/likeIds-context";
import {getToken} from "../../../utils/token";
import {reqGetArticleCommentsLength} from "../../../api/frontDesk/article";

const tabListNoTitle = [
    {
        key: 'recommend',
        tab: '推荐',
    },
    {
        key: 'new',
        tab: '最新',
    },
    {
        key: 'hot',
        tab: '最热',
    },
];

const Home = () => {
    const [activeTabKey1, setActiveTabKey1] = useState('recommend');
    const [activeTabKey2, setActiveTabKey2] = useState('new');

    //使用钩子提取redux的数据
    const dispatch = useDispatch()
    const {homeArticleList} = useSelector(state => state.persistedReducer.article || [])
    const {userAllInfo} = useSelector(state => state.persistedReducer.user)
    const [ids, setIds] = useState([])
    const [likeIds, setLikeIds] = useState({})
    const [sortList, setSortList] = useState([])
    const [dateList, setDateList] = useState([])
    // 滚动时隐藏导航栏
    const [hide, setHide] = useState(false)
    //文章评论数量
    const [commentNums, setCommentNums] = useState([])


    useEffect(() => {
        window.addEventListener('scroll', onScroll, true)
    }, [])
    const onScroll = () => {
        let top = document.documentElement.scrollTop || document.body.scrollTop || window.pageYOffset
        if (top > 300) {
            setHide(true)
        } else {
            setHide(false)
        }
    }


    //获取文章列表
    useEffect(() => {
        dispatch(getArticleIntro())
    }, [])

    //进行排列
    useEffect(() => {
        const newList = [...homeArticleList]
        const newList1 = [...homeArticleList]
        setSortList(newList.sort((a, b) => b.praise - a.praise).filter((item, index) => index < 3))
        setDateList(() => newList1.sort((a, b) => b.create_time - a.create_time).filter(item => {
            const itemDate = new Date(item.create_time);
            const may5 = new Date('2023-05-04'); // 替换为实际需要的日期
            return itemDate > may5;
        }))
    }, [])

    //获取文章id
    useEffect(() => {
        const ids = homeArticleList.map((item) => item.id)
        setIds(ids)
    }, [homeArticleList])

    // 获取文章赞数
    useEffect(() => {
        const getData = async () => {
            await reqGetArticleLikes()
        }
        getData()
    }, [ids])

    //获取文章评论数量
    useEffect(() => {
        const getCommentLength = async () => {
            const result = await reqGetArticleCommentsLength()
            setCommentNums(result.data)
        }
        getCommentLength()
    }, [])


    //判断用户是否点赞
    useEffect(() => {
        const getData = async () => {
            const result = await reqGetJudgeLike({
                user_id: userAllInfo.id,
                article_ids: ids
            });
            setLikeIds(result.data)
        };
        if (ids.length > 0 && userAllInfo.id) {
            getData();
        }
    }, [ids])


    const onTab1Change = (key) => {
        setActiveTabKey1(key)
    }
    const onTab2Change = (key) => {
        setActiveTabKey2(key)
    }


    const filterArticle = (id) => {
        const newList = homeArticleList.filter((item) => item.id !== id)
        dispatch(updateArticleList(newList))
    }


    const contentListNoTitle = {
        recommend: <div>
            {
                homeArticleList.map((item) =>
                    <Article
                        comments={commentNums}
                        key={item.id}
                        onConfirm={() => filterArticle(item.id)}
                        article={item}
                    >
                        {
                            commentNums.map((item1) => {
                                if (item1.id===item.id){
                                    return <span>
                                        {item1.comment_count}
                                    </span>
                                }
                            })
                        }
                    </Article>
                )
            }
        </div>,
        new: <div>
            {dateList.map((item) => <Article key={item.id} article={item}/>)}
        </div>,
        hot: <div>
            {sortList.map((item) => <Article key={item.id} article={item}/>)}
        </div>,
    }


    const [likedMap, setLikedMap] = useState({});
    const [open, setOpen] = useState(false)

    useEffect(() => {
        if (Object.keys(userAllInfo).length !== 0) {
            const newLikedMap = {};
            ids.forEach((id) => {
                newLikedMap[id] = !!likeIds[id];
            });
            setLikedMap(newLikedMap);
        }
    }, [ids, likeIds, userAllInfo]);

//点赞
    const like = async (id) => {
        console.log(id)
        if (getToken()) {
            // e.preventDefault()
            //发起请求
            // if (onClick) onClick(e)
            await reqLike({user_id: userAllInfo.id, article_id: id})
            const result = await reqGetArticleLikes()
            if (result.status === 0) {
                const isLiked = result.data.find((like) => like.id === id)
                setLikedMap((prevState) => ({...prevState, [id]: !!isLiked}))
                dispatch(getArticleIntro())
            }
        } else {
            setOpen(!open)
        }
    }

//取消点赞
    const cancelLike = async (id) => {
        console.log(id)
        if (getToken()) {
            await reqLike({user_id: userAllInfo.id, article_id: id, cancel: '取消'})
            const result = await reqGetArticleLikes();
            if (result.status === 0) {
                const isLiked = result.data.find((like) => like.article_id === id);
                setLikedMap((prevState) => ({...prevState, [id]: !!isLiked}));
                dispatch(getArticleIntro())
            }
        }
    }

    return (
        <div>
            <div className={hide === false ? `block` : `hide`}>
                <Sort/>
            </div>
            <>
                <likeIdsContext.Provider value={{likeIds, ids, like, cancelLike, open, likedMap}}>
                    <div className={classes.Home}>
                        <Card
                            style={{width: '70%'}}
                            tabList={tabListNoTitle}
                            activeTabKey={activeTabKey1}
                            onTabChange={(key) => {
                                onTab1Change(key)
                                onTab2Change(key);
                            }}
                        >
                            {contentListNoTitle[activeTabKey1]}
                        </Card>
                        <div style={{width: 280}}>
                            <Card
                                bodyStyle={{padding: "unset"}}
                                title="文章排行榜"
                                className={classes.RankContainer}
                            >
                                {
                                    sortList.map((item) => (
                                        <Skeleton
                                            key={item.id}
                                            loading={false}
                                            avatar
                                            active
                                            paragraph={{rows: 1}}>
                                            <div onClick={() => {
                                                history.push(`/article-content/${item.id}`)
                                            }} className={classes.ArticleRank}>
                                                <Avatar className={classes.ArticleCover} src={item.cover}/>
                                                <div className={classes.RankDescribe}>
                                                    <span className={classes.ArticleRankTitle}>{item.title}</span>
                                                    <span>{item.sort}</span>
                                                </div>
                                            </div>
                                        </Skeleton>
                                    ))
                                }

                            </Card>
                            <div>
                                <Calendar
                                    locale={locale}
                                    className={classes.Calendar}
                                    fullscreen={false}/>
                            </div>
                        </div>
                    </div>
                </likeIdsContext.Provider>
            </>
        </div>
    );
};

export default Home;